package cn.highedu.config;

import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class Fastjson2Config implements WebMvcConfigurer {

    private Logger logger = LoggerFactory.getLogger(Fastjson2Config.class);

    /**
     * 自定义Fastjson消息转换器
     */
    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
        // 创建FastJson消息转换器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        // 创建FastJson配置对象
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 设置FastJson配置
        fastJsonConfig.setCharset(java.nio.charset.StandardCharsets.UTF_8);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置FastJson转换器配置
        fastJsonConverter.setFastJsonConfig(fastJsonConfig);
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        fastJsonConverter.setSupportedMediaTypes(supportedMediaTypes);
        return fastJsonConverter;
    }

    /**
     * 测试检查消息转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        for(HttpMessageConverter<?> messageConverter: converters){
            logger.debug("{}", messageConverter.getClass().getName());
        }
    }

}
